package com.nd.service;


import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.nd.dao.TopicMapper;
import com.nd.pojo.bean.Coupon;
import com.nd.pojo.bean.CouponExample;
import com.nd.pojo.bean.Topic;
import com.nd.pojo.bean.TopicExample;
import com.nd.pojo.vo.AdQueryDataVo;
import com.nd.pojo.vo.CouponQueryVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Service
public class TopicServiceImpl implements TopicService {

    @Autowired
    TopicMapper topicMapper;

    @Override
    public AdQueryDataVo queryAll(Integer page, Integer limit, String sort, String order, String title, String subtitle) {

        PageHelper.startPage(page, limit);
        TopicExample topicExample = new TopicExample();

        //排序信息
        topicExample.setOrderByClause(sort + " " + order);
        TopicExample.Criteria criteria = topicExample.createCriteria();

        criteria.andDeletedEqualTo(false);

        if (title != null && !"".equals(title)) {
            criteria.andTitleLike("%" + title + "%");
        }
        if (subtitle != null && !"".equals(subtitle)) {
            criteria.andSubtitleLike("%" + subtitle + "%");
        }

        List<Topic> topics = topicMapper.selectByExampleWithBLOBs(topicExample);


        //List<CouponQueryVo> couponQueryVos = new ArrayList<>();



        //可以获得分页信息
        PageInfo<Topic> userPageInfo = new PageInfo<>(topics);
        long total = userPageInfo.getTotal();

        AdQueryDataVo topicQueryDataVo = new AdQueryDataVo();
        topicQueryDataVo.setTotal((int)total);
        topicQueryDataVo.setItems(topics);


        return topicQueryDataVo;


    }

    @Override
    public Integer delete(Integer id) {

        TopicExample topicExample = new TopicExample();

        TopicExample.Criteria criteria = topicExample.createCriteria();

        criteria.andIdEqualTo(id);

        Topic topic = new Topic();

        topic.setDeleted(true);

        Integer code = topicMapper.updateByExampleSelective(topic, topicExample);

        return code;


    }

    @Override
    public Topic create(Topic topic) {

        Date date = new Date();

        topic.setAddTime(date);
        topic.setUpdateTime(date);

        int i = topicMapper.insertSelective(topic);


        return topic;
    }

    @Override
    public Topic update(Topic topic) {

        TopicExample topicExample = new TopicExample();

        TopicExample.Criteria criteria = topicExample.createCriteria();

        criteria.andIdEqualTo(topic.getId());

        topic.setUpdateTime(new Date());

        topicMapper.updateByExampleSelective(topic, topicExample);


        return topic;
    }
}
